//
//  landingViewController.m
//  Food
//
//  Created by 15 on 15/7/21.
//  Copyright (c) 2015年 李志远. All rights reserved.
//

#import "landingViewController.h"
#import "AppDelegate.h"
#import "HomePageViewController.h"
#import "UserInfo.h"
#import <MOBFoundation/MOBFoundation.h>
#import <MOBFoundation/MOBFImageService.h>
#import <ShareSDKExtension/SSEThirdPartyLoginHelper.h>
#import "CollectionViewController.h"

#import "AboutUsController.h"

#import "feedbackViewController.h"


#define ImageHeight 170.0f
#define IS_WIDESCREEN ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )568 ) < DBL_EPSILON )
@interface landingViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>
@property (nonatomic, retain) UITableView *myTableView;
@property (nonatomic, retain) UIImageView *backView;
@property (nonatomic, retain) UIButton *userButton;
@property (nonatomic, strong) UIImageView *avatarImageView;
@property (nonatomic, strong) UILabel *nicknameLabel;
@property (nonatomic, strong) UILabel *aboutMeLabel;
@property (nonatomic, strong) UILabel *tipsLabel;
@property (nonatomic, retain) UIButton *cancelButton;
@property (nonatomic, retain) UserInfo *currentUser;
@property (nonatomic, retain) UIAlertView *alert;
@property (nonatomic, retain) NSMutableArray *imagesArr1;
@property (nonatomic, retain) NSMutableArray *imagesArr2;
@property (nonatomic, retain) NSMutableArray *arr1;
@property (nonatomic, retain) NSMutableArray *arr2;

@end

@implementation landingViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        //设置用户类型为UserInfo，这样可以将自定义的用户信息类与第三方登录进行绑定
        [SSEThirdPartyLoginHelper setUserClass:[UserInfo class]];
    }
    
    return self;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
   // self.tabBarController.tabBar.translucent = NO;
    [self.navigationItem setLeftBarButtonItem:nil animated:NO];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"iconfont-shouyezuoshangchoutilan"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(click)];
   
    //self.cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    //[self.cancelButton setTitle:@"注销" forState:UIControlStateNormal];
//    [self.cancelButton setImage:[[UIImage imageNamed:@"iconfont-tuichudenglu"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
//    [self.cancelButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
//    self.cancelButton.frame = CGRectMake(0, 0, 20, 20);
//    [self.cancelButton addTarget:self action:@selector(cancel:) forControlEvents:UIControlEventTouchUpInside];
//   
//    UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithCustomView:self.cancelButton];
//    self.navigationItem.rightBarButtonItem = right;
//    
    
    if ([MOBFDevice versionCompare:@"7.0"] >= 0)
    {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.extendedLayoutIncludesOpaqueBars = YES;
    }
    [self.navigationItem.leftBarButtonItem release];
   // [right release];
    [self createView];
    self.imagesArr1 = [NSMutableArray arrayWithObjects:@"iconfont-dongtaiyemianxiaotubiao03",@"iconfont-shezhiqingchuhuancun@2x", nil];
    self.imagesArr2 = [NSMutableArray arrayWithObjects:@"iconfont-icon071-3",@"iconfont-yijianfankui-2", nil];
    self.arr1 = [NSMutableArray arrayWithObjects:@"我的收藏",@"清除缓存", nil];
    self.arr2 = [NSMutableArray arrayWithObjects:@"关于我们",@"意见反馈", nil];
    
}

#pragma mark- 注销

- (void)cancel:(UIButton *)button
{
    NSLog(@"z注销");
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"是否确认注销" delegate:self cancelButtonTitle:@"NO" otherButtonTitles:@"YES", nil];
    [alert show];
    [alert release];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [SSEThirdPartyLoginHelper logout:self.currentUser];
        [self refreshUserInfo];
    }
    
    if (alertView.tag == 6001) {
        if (buttonIndex == 1) {
            NSLog(@"清除");
            float tmpSize = [[SDImageCache sharedImageCache] checkTmpSize];
            [[SDImageCache sharedImageCache] clearDisk];
            NSString *clearName = tmpSize >= 1 ? [NSString stringWithFormat:@"成功清除缓存(%.2fM)",tmpSize]:[NSString stringWithFormat:@"成功清除缓存(%.2fK)",tmpSize * 1024];
            _alert = [[UIAlertView alloc] initWithTitle:@"提示" message:clearName delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
            
            [_alert show];
            [_alert release];
            [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(DISSMISS) userInfo:nil repeats:NO];
            
        }
    }
    
}


- (void)click
{
    [self showMenu];
}

- (void)showMenu
{
    if (!_sideMenu) {
        RESideMenuItem *more = [[RESideMenuItem alloc] initWithTitle:@"更多" action:^(RESideMenu *menu, RESideMenuItem *item) {
            
        }];
        
        RESideMenuItem *landing = [[RESideMenuItem alloc] initWithTitle:@"我的" image:[UIImage imageNamed:@"iconfont-wode"] highlightedImage:nil action:^(RESideMenu *menu, RESideMenuItem *item) {
            self.hidesBottomBarWhenPushed = NO;
            self.navigationController.navigationBarHidden = NO;
            landingViewController *land = [[landingViewController alloc] init];
            UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:land];
            land.title = item.title;
            [menu setRootViewController:navi];
        }];
        
        RESideMenuItem *returnMain = [[RESideMenuItem alloc] initWithTitle:@"返回主页" image:[UIImage imageNamed:@"iconfont-zhuye"] highlightedImage:nil action:^(RESideMenu *menu, RESideMenuItem *item) {
            AppDelegate *app = [UIApplication sharedApplication].delegate;
            [menu setRootViewController:app.rootTBC];
        }];
        _sideMenu = [[RESideMenu alloc] initWithItems:@[more, landing, returnMain]];
        _sideMenu.verticalOffset = IS_WIDESCREEN ? 20 : 20;
        _sideMenu.hideStatusBarArea = [AppDelegate OSVersion] < 3;
    }
    [_sideMenu show];

}


- (void)createView
{
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64) style:UITableViewStyleGrouped];
    self.myTableView.dataSource = self;
    self.myTableView.delegate = self;
   // self.myTableView.contentInset = UIEdgeInsetsMake(ImageHeight, 0, 0, 0);
    [self.myTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.myTableView release];

    [self.view addSubview:self.myTableView];
    self.backView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ImageHeight)];
    self.backView.image = [UIImage imageNamed:@"user"];
    self.backView.backgroundColor = [UIColor lightGrayColor];
    self.backView.userInteractionEnabled = YES;
    self.backView.contentMode = UIViewContentModeScaleAspectFill;
    self.backView.clipsToBounds = YES;
    self.myTableView.tableHeaderView = self.backView;
    [self.myTableView addSubview:self.backView];
    [self.backView release];

//    self.userButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    self.userButton.backgroundColor = [UIColor clearColor];
////    [self.userButton setBackgroundImage:[UIImage imageNamed:@"picholder_profile@2x"] forState:UIControlStateNormal];
//    self.userButton.frame = CGRectMake(110, 100, 100, 30);
//    [self.userButton addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
//    //self.userButton.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
//    [self.backView addSubview:self.userButton];
//    //提示
//    self.tipsLabel = [[UILabel alloc] initWithFrame:CGRectMake(110, 100, 100, 30)];
//    self.tipsLabel.font = [UIFont systemFontOfSize:16];
//    [self.backView addSubview:self.tipsLabel];
//    [self.tipsLabel release];
//    //头像
//    self.avatarImageView = [[UIImageView alloc] initWithFrame:CGRectMake(110, 20, 100, 100)];
//    self.avatarImageView.layer.cornerRadius = 50;
//    self.avatarImageView.layer.masksToBounds = YES;
//    [self.backView addSubview:self.avatarImageView];
//    [self.avatarImageView release];
//    //昵称
//    self.nicknameLabel = [[UILabel alloc] initWithFrame:CGRectZero];
//    self.nicknameLabel.textAlignment = NSTextAlignmentCenter;
//    self.nicknameLabel.font = [UIFont systemFontOfSize:16];
//    [self.backView addSubview:self.nicknameLabel];
//    [self.nicknameLabel release];
//    //关于
////    self.aboutMeLabel = [[UILabel alloc] initWithFrame:CGRectZero];
////    self.aboutMeLabel.font = [UIFont systemFontOfSize:16];
////    self.aboutMeLabel.numberOfLines = 0;
////    [self.backView addSubview:self.aboutMeLabel];
//
//    [self refreshUserInfo];

}

/**
 *  刷新用户信息
 */
- (void)refreshUserInfo
{
    self.currentUser = (UserInfo *)[SSEThirdPartyLoginHelper currentUser];
    if (self.currentUser)
    {
        self.avatarImageView.hidden = NO;
        self.nicknameLabel.hidden = NO;
        self.tipsLabel.hidden = YES;
        self.userButton.hidden = YES;
        self.nicknameLabel.text = self.currentUser.nickname;
        [self.tipsLabel sizeToFit];
        [self.nicknameLabel sizeToFit];
        self.nicknameLabel.frame = CGRectMake(100, 130, 120, 30);
        
        self.cancelButton.hidden = NO;
        

        if (self.currentUser.avatar)
        {
            NSString *observer = [self description];
            __block landingViewController *theController = self;
            [[MOBFImageService sharedInstance] getImageWithURL:[NSURL URLWithString:self.currentUser.avatar]
                                                      observer:observer
                                                     onLoading:nil
                                                      onResult:^(NSData *imageData) {
                                                          
                                                          theController.avatarImageView.image = [[UIImage alloc] initWithData:imageData];
                                                          [[MOBFImageService sharedInstance] removeObserver:observer];
                                                          
                                                      }
                                                        onFail:nil];
        }
        
//        self.aboutMeLabel.text = self.currentUser.aboutMe;
//        self.aboutMeLabel.frame = [self.aboutMeLabel textRectForBounds:CGRectMake(self.avatarImageView.frame.origin.x, self.avatarImageView.frame.origin.y + self.avatarImageView.frame.size.height, self.view.frame.size.width - 40, MAXFLOAT) limitedToNumberOfLines:0];
    }
    else
    {
        self.avatarImageView.hidden = YES;
        self.nicknameLabel.hidden = YES;
        self.tipsLabel.hidden = NO;
        self.userButton.hidden = NO;
        self.cancelButton.hidden = YES;
        self.tipsLabel.text = @"点击这里登录";
        self.tipsLabel.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin;
        [self.tipsLabel sizeToFit];
//        //self.tipsLabel.frame = CGRectMake((self.view.frame.size.width - self.tipsLabel.frame.size.width) / 2,
//                                          (self.view.frame.size.height - self.tipsLabel.frame.size.height) / 2,
//                                          CGRectGetWidth(self.tipsLabel.frame),
//                                          CGRectGetHeight(self.tipsLabel.frame));
    }
}



- (void)click:(UIButton *)button
{
    NSLog(@"登录");
    [SSEThirdPartyLoginHelper loginByPlatform:SSDKPlatformTypeSinaWeibo onUserSync:^(SSDKUser *user, SSEUserAssociateHandler associateHandler) {
        associateHandler (user.uid,user,user);
    } onLoginResult:^(SSDKResponseState state, SSEBaseUser *user, NSError *error) {
        if (state == SSDKResponseStateSuccess) {
            [self refreshUserInfo];
        }
    }];
    
    
    
    
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 2;
    } else if (section == 1) {
        return 2;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (indexPath.section == 0) {
        cell.textLabel.text = self.arr1[indexPath.row];
        
        NSString *name = self.imagesArr1[indexPath.row];
        cell.imageView.image = [UIImage imageNamed:name];
    }
        if (indexPath.section == 1) {
        cell.textLabel.text = self.arr2[indexPath.row];
        NSString *name = self.imagesArr2[indexPath.row];
        cell.imageView.image = [UIImage imageNamed:name];
    }
    return cell;
}

#pragma mark- 跳转收藏页面

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        
        if (indexPath.row == 0) {
            CollectionViewController *collectionVC = [[[CollectionViewController alloc] init] autorelease];
            [self.navigationController pushViewController:collectionVC animated:YES];
        }if (indexPath.row == 1) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"是否清除缓存?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            alert.tag = 6001;
            [alert show];
            [alert release];
    }
    }

       else if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            AboutUsController *aboutVC = [[AboutUsController alloc] init];
            aboutVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:aboutVC animated:YES];
            
        }if (indexPath.row == 1) {
            feedbackViewController *about = [[[feedbackViewController alloc] init] autorelease];
            [self.navigationController pushViewController:about animated:YES];
            
        }
       }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 45;
}
//分区尾
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 5.f;
}
//分区头
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20.f;
}


- (void)DISSMISS
{
    //UIAlertView *ALERT = (UIAlertView *)[self.view viewWithTag:2000];
    
    [_alert dismissWithClickedButtonIndex:0 animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
